package com.example.mybatisdemo.service.impl;

import com.example.mybatisdemo.dao.UserDao;
import com.example.mybatisdemo.entity.User;
import com.example.mybatisdemo.service.UserService;
import com.example.mybatisdemo.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

// 用户服务实现类，实现 UserService 接口
public class UserServiceImpl implements UserService {
    @Override
    public int addUser(User user) {
        int result = 0;
        SqlSession sqlSession = null;
        try {
            // 获取 SqlSession 实例
            sqlSession = MyBatisUtil.getSqlSession();
            // 获取 UserDao 接口的实现类对象
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            // 调用插入方法
            result = userDao.insertUser(user);
            // 提交事务
            sqlSession.commit();
        } catch (Exception e) {
            // 回滚事务
            if (sqlSession != null) {
                sqlSession.rollback();
            }
            e.printStackTrace();
        } finally {
            // 关闭 SqlSession
            if (sqlSession != null) {
                sqlSession.close();
            }
        }


        return result;
    }
}
